package com.fh.shop.api.product.biz;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.Product;
import com.fh.shop.util.ServerResponse;
import com.fh.shop.api.product.vo.ProductVo;
import com.fh.shop.util.RedisUtil;
import com.fh.shop.mapper.IProductMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service("productService")
public class IProductServiceImpl implements IProductService {
    @Resource
    private IProductMapper productMapper;

    @Override
    public ServerResponse findList() {
        //先到redis缓存中取
        String productImg = RedisUtil.get("productList");
        if (StringUtils.isNotEmpty(productImg)){
            //转换成java对象
            List<ProductVo> productVos = JSON.parseArray(productImg, ProductVo.class);
            return ServerResponse.success(productVos);
        }
        //否则去数据库查询
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        //为了提高性能，查询只需要的字段
        queryWrapper.eq("status",1)
                .eq("recommend",1)
                .eq("newProduct",1)
                .select("id","productName","price","mainImage");
        List<Product> productList = productMapper.selectList(queryWrapper);
        List<ProductVo> productVoList = productList.stream().map(x -> {
            ProductVo productVo = new ProductVo();
            productVo.setId(x.getId());
            productVo.setProductName(x.getProductName());
            productVo.setPrice(x.getPrice().toString());
            productVo.setMainImage(x.getMainImage());
            return productVo;
        }).collect(Collectors.toList());
        //转换为json格式的字符串
        String productJson = JSON.toJSONString(productVoList);
        //放入redis缓存中
        RedisUtil.setex("productList",productJson,10 * 60);
        return ServerResponse.success(productVoList);
    }
}
